package qcmPlus.tools;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class HibernateUtil {

    private static final SessionFactory sessionFactory;
    private static final boolean JTA_ENABLED = false;
    
    static {
        try {
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static final ThreadLocal<Session> session = new ThreadLocal<Session>();

    public static Session currentSession() throws HibernateException {
        Session s = (Session) session.get();
        if (s == null) {
            s = sessionFactory.openSession();
            if(!JTA_ENABLED)
            	s.beginTransaction();
            session.set(s);
        }
        return s;
    }

    public static void closeSession() throws HibernateException {
        Session s = (Session) session.get();
        session.set(null);
        if (s != null && s.isOpen()) {
        	s.flush();
            if(!JTA_ENABLED)
            	s.getTransaction().commit();
        	s.close();
        }
    }
    
    public static void schemaExport() {
		try {
			Configuration cfg = new Configuration().configure();
			new SchemaExport(cfg).create(true, true);		
		} catch(Exception e) {
			
			e.printStackTrace();
		}
    }
}
